package Clases;

import Presentacion.Principal;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.beans.*;
import java.util.Random;

public class BarraProgreso implements PropertyChangeListener {

    private JProgressBar progressBar;
    private Task task;
    private JButton boton;
    Principal principal;

    public void BarraProgreso() {
        progressBar = new JProgressBar(0, 100);
        progressBar.setValue(0);
        progressBar.setStringPainted(true);
    }

    public JButton getBoton() {
        return boton;
    }

    class Task extends SwingWorker<Void, Void> {

        @Override
        protected Void doInBackground() throws Exception {
            Random random = new Random();
            int progress = 0;
            //Initialize progress property.
            setProgress(0);
            while (progress < 100) {
                //Sleep for up to one second.
                try {
                    Thread.sleep(random.nextInt(1000));
                } catch (InterruptedException ignore) {
                }
                //Make random progress.
                progress += random.nextInt(10);
                setProgress(Math.min(progress, 100));
            }
            return null;
        }

        @Override
        public void done() {
            Toolkit.getDefaultToolkit().beep();
            getBoton().setEnabled(true);
            principal.setCursor(null);
        }
    }

    @Override
    public void propertyChange(PropertyChangeEvent evt) {
        if ("progress".equals(evt.getPropertyName())) {
            int progress = (Integer) evt.getNewValue();
            progressBar.setValue(progress);
        }
    }

    /*invocarlo al dar click*/
    public void accionBoton(JButton boton, Principal p) {
        this.boton = boton;
        this.boton.setEnabled(false);
        principal = p;
        principal.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        task = new Task();
        task.addPropertyChangeListener(this);// en vez d este this hay q mandarle la ventana 
        task.execute();
    }
}
